package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.mongo.VisitorService;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
@DubboService
public class VisitorServiceImpl implements VisitorService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public List<Visitor> findVisitorsTop5(Long userId, Long lastAccessTime) {
        //1.创建条件对象(登陆者id,时间,排序,分页)
        Query query = new Query(Criteria.where("userId").is(userId).and("date").gte(lastAccessTime))
                .with(Sort.by(Sort.Order.desc("date")))
                .limit(5);

        //2.查询visitor表中前五条数据且返回
        return mongoTemplate.find(query,Visitor.class);
    }

    @Override
    public PageBeanVo topVisitor(Long userId, Integer pageNumber, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize, Sort.by(Sort.Order.desc("date")));
        Query query=new Query(Criteria.where("userId").is(userId)).with(pageRequest);

        List<Visitor> visitors = mongoTemplate.find(query, Visitor.class);
        for (Visitor visitor : visitors) {
            Query query1=new Query(Criteria
                    .where("userId").is(visitor.getVisitorUserId())
                    .and("toUserId").is(visitor.getUserId()));
            RecommendUser one = mongoTemplate.findOne(query1, RecommendUser.class);
            if (one!=null){
                visitor.setScore(one.getScore());
            }else {
                visitor.setScore(20.0);
            }
        }

        PageBeanVo pageBeanVo=new PageBeanVo();
        pageBeanVo.setItems(visitors);
        pageBeanVo.setPage(pageNumber);
        pageBeanVo.setPagesize(pageSize);


        return pageBeanVo;
    }
}
